//
//  StatusView.swift
//  MIFI
//
//  Created by 金嗓子卡卡 on 2019/4/20.
//  Copyright © 2019 NJMifi. All rights reserved.
//

import UIKit

class StatusView: UIView {

    private let maxCount = 30
    private var alertPercent = 0
    private var usedPercent = 0
    private var changeAnimalIndex = 1
    
    
    var remianMemory : CGFloat = 0
    
    private var startDrees : CGFloat = (60.0 / 180) * .pi
    
    private let endDrees : CGFloat = -(1 + 60.0 / 180) * .pi
    
    private let mInactiveColor = colorStr(color: "#15C8B3")
    private let mInactiveRedColor = colorStr(color: "#DC1F1F")
    private let mInactiveBlueRedColor = colorStr(color: "#FFAA1B")
    private var mInactiveGrayColor = UIColor.gray
    
    private var memoryPath:UIBezierPath?
    
    private lazy var drees: CGFloat = {
        return (endDrees - startDrees) / CGFloat(maxCount)
    }()
    
    var connect : Bool = false {
        didSet{
            mInactiveGrayColor = connect ? colorStr(color: "#1AFD9C") : UIColor.gray
            layoutIfNeeded()
        }
    }
    
    private lazy var networkTypeLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 20, y: width / 5, width: width / 3, height: width / 5))
        label.right = width / 2
        label.backgroundColor = clearColor
        label.textColor = whiteColor
        label.textAlignment = .right
        label.font = UIFont.systemFont(ofSize: 15)
        label.text = "2G"
        label.lineBreakMode = .byClipping
        label.isHidden = true
        return label
    }()
    
    private lazy var signStrengthImageV: UIImageView = {
        let imageV = UIImageView(frame: CGRect(x: networkTypeLabel.right + 10, y: networkTypeLabel.top, width: height / 6 * 0.77, height: height / 7 * 0.77))
        imageV.centerY = networkTypeLabel.centerY
        imageV.image = UIImage(named: "r_signal_0")
        imageV.isHidden = true
        return imageV
    }()
    
    private lazy var leftMemoryLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: width - 20 * 2, height: height / 5))
        label.centerX = width / 2
        label.centerY = height / 2
        label.font = UIFont.systemFont(ofSize: 14)
        label.textAlignment = .center
        label.backgroundColor = clearColor
        label.textColor = whiteColor
        label.text = "left 9999.09MB"
        label.isHidden = true
        return label
    }()
    
    private lazy var totalMemoryLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: leftMemoryLabel.left + 8, y: leftMemoryLabel.bottom, width: leftMemoryLabel.width - 8 * 2, height: 20))
        label.backgroundColor = clearColor
        label.textAlignment = .center
        label.textColor = blackColor
        label.text = "Total 9999MB"
        label.font = UIFont.systemFont(ofSize: 14)
        label.isHidden = true
        return label
    }()
    
    
    func changeBackToGreen(){
        
        if self.layer.sublayers != nil {
            
            for itme in self.layer.sublayers! {
                
                if itme.isMember(of: CAShapeLayer.classForCoder()){
                    itme.removeFromSuperlayer()
                }
                
            }
            
        }
        
        startDrees = (60.0 / 180) * .pi
        for index in 0..<maxCount {

            let layer:CAShapeLayer = CAShapeLayer()
            
            
            let path = UIBezierPath(arcCenter: CGPoint(x: width/2, y: height/2),
                                    radius: height / 2 - 15,
                                    startAngle: startDrees,
                                    endAngle: startDrees + drees + (2.0/180) * .pi,
                                    clockwise: false)
            
            if index == maxCount - 1 {
                startDrees = (60.0 / 180) * .pi
            }else {
                startDrees += drees
            }
            layer.path = path.cgPath
            layer.lineWidth  = 10
            
            layer.strokeColor = mInactiveColor.cgColor
            
            
            self.layer.addSublayer(layer)
            
        }
    }
    
    func changeBackToGray(){
    
        if self.layer.sublayers != nil {
            
            for itme in self.layer.sublayers! {
                
                if itme.isMember(of: CAShapeLayer.classForCoder()){
                    itme.removeFromSuperlayer()
                }
                
            }
            
        }
        
        
        
        startDrees = (60.0 / 180) * .pi
        for index in 0..<maxCount {
            
            let layer:CAShapeLayer = CAShapeLayer()
            let path = UIBezierPath(arcCenter: CGPoint(x: width/2, y: height/2),
                                    radius: height / 2 - 15,
                                    startAngle: startDrees,
                                    endAngle: startDrees + drees + (2.0/180) * .pi,
                                    clockwise: false)
            
            if index == maxCount - 1 {
                startDrees = (60.0 / 180) * .pi
            }else {
                startDrees += drees
            }
            layer.path = path.cgPath
            layer.lineWidth  = 10
            layer.strokeColor = mInactiveGrayColor.cgColor
            self.layer.addSublayer(layer)
            
        }
    }
    
    private func changeMemoryDraw(){
        
        
        if self.layer.sublayers != nil {
            
            for itme in self.layer.sublayers! {
                
                if itme.isMember(of: CAShapeLayer.classForCoder()){
                     itme.removeFromSuperlayer()
                }
                
            }
            
        }
        
//        if changeAnimalIndex % 7 != 1 {
//
//            changeAnimalIndex = changeAnimalIndex + 1
//            return;
//
//        }
           changeAnimalIndex = changeAnimalIndex + 1
        
         startDrees = (60.0 / 180) * .pi
        
        var pathAll:UIBezierPath?
        
        for index in 0..<maxCount {

            let layer:CAShapeLayer = CAShapeLayer()
            let path = UIBezierPath(arcCenter: CGPoint(x: width/2, y: height/2),
                                    radius: height / 2 - 15,
                                    startAngle: startDrees,
                                    endAngle: startDrees + drees + (2.0/180) * .pi,
                                    clockwise: false)
            
        
            if index == 0{
               pathAll = path
            }
             //逆时针排序
            if index == maxCount - 1 {
                startDrees = (60.0 / 180) * .pi
            }else {
                startDrees += drees
            }
            layer.path = path.cgPath
            layer.lineWidth  = 10
            
            let currentIndex = maxCount - index
            
            let used = Double(usedPercent) / 100.0 * Double(maxCount)
            
            let alert = Double(alertPercent) / 100.0 * Double(maxCount)
             
            
            if currentIndex < Int(used) {
                
                layer.strokeColor = mInactiveRedColor.cgColor
                
            }else if currentIndex < Int(alert)   {
                layer.strokeColor = mInactiveColor.cgColor
            }else {
                
                layer.strokeColor = mInactiveBlueRedColor.cgColor
                
            }
            

            
            
            if !UserInfoManager.shared().data_volume_limit_switch {
             layer.strokeColor = mInactiveColor.cgColor
            }
            
              self.layer.addSublayer(layer)

        }

       print("当前的时间：\(NSDate())")
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        configView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func configView() {
        
        backgroundColor = clearColor
        addSubview(networkTypeLabel)
        addSubview(signStrengthImageV)
        addSubview(leftMemoryLabel)
        addSubview(totalMemoryLabel)
      
    }

    
    func refreshData(data:StatusVCDeviceInfoModel?) {
        if data != nil {
            networkTypeLabel.isHidden = false
            networkTypeLabel.text = checkType(type: data!.network_type)
            let imageName = data!.simcard_roam!.caseInsensitiveCompare("home") == .orderedSame ? "signal_" : "r_signal_"
            signStrengthImageV.image = UIImage(named: "\(imageName)\(data!.signalbar!)")
            signStrengthImageV.isHidden = false
            refreshMemonry(status: data!)
        }else {
            networkTypeLabel.isHidden = true
            signStrengthImageV.isHidden = true
            changeBackToGray()
        }
        
        leftMemoryLabel.isHidden = data?.loginfo != "ok"
        totalMemoryLabel.isHidden = leftMemoryLabel.isHidden
        
    }
    
    private func checkType(type:String?) -> String{
        var string = type != nil ? type! : ""
        if string.caseInsensitiveCompare("GSM") == .orderedSame ||
            string.caseInsensitiveCompare("GPRS") == .orderedSame ||
            string.caseInsensitiveCompare("EDGE") == .orderedSame
        {
            string = "2G"
        }else if string.caseInsensitiveCompare("UMTS") == .orderedSame ||
            string.caseInsensitiveCompare("HSDPA") == .orderedSame ||
            string.caseInsensitiveCompare("HSUPA") == .orderedSame ||
            string.caseInsensitiveCompare("HSPA") == .orderedSame ||
            string.caseInsensitiveCompare("HSPA+") == .orderedSame ||
            string.caseInsensitiveCompare("DC-HSPA+") == .orderedSame ||
            string.caseInsensitiveCompare("WCDMA") == .orderedSame{
            string = "3G"
        }else if string.caseInsensitiveCompare("LTE") == .orderedSame {
            string = "4G"
        }else {
            if string.caseInsensitiveCompare("LIMITED_SERVICE") == .orderedSame {
                
            }else if string.caseInsensitiveCompare("LIMITED_SERVICE_WCDMA") == .orderedSame {
                string = "2G"
            }else if string.caseInsensitiveCompare("LIMITED_SERVICE_GSM") == .orderedSame {
                string = "3G"
            }else if string.caseInsensitiveCompare("LIMITED_SERVICE_LTE") == .orderedSame {
                string = "4G"
            }else {
                
            }
        }

        return string
    }

    
    private func refreshMemonry(status:StatusVCDeviceInfoModel) {
        let totalStr = status.data_volume_limit_size
        guard totalStr != nil && totalStr!.count > 0 else {
            return
        }
        if status.data_volume_alert_percent != nil && status.data_volume_alert_percent!.count > 0{
            alertPercent = Int(status.data_volume_alert_percent!)!
            UserInfoManager.shared().alertPercent = "\(alertPercent)"
        }
        UserInfoManager.shared().data_volume_limit_switch = status.data_volume_limit_switch == "1"
        UserInfoManager.shared().data_volume_limit_unit = status.data_volume_limit_unit == "data" ? "Data" : "Time"
        
        if status.data_volume_limit_unit!.caseInsensitiveCompare("data") == .orderedSame {
            var sharedTotalSize = ""
            var arr = totalStr!.components(separatedBy: "_")
            if isEmpty(string: arr[0]){
                arr[0] = "0"
            }
            let totalSize = Double(arr[0].replacingOccurrences(of: " MB", with: "").replacingOccurrences(of: " h", with: ""))!
            let unitValue = Int(arr[1])!
            var unit = ""
            if unitValue == 1 {
                unit = "MB"
                totalMemoryLabel.text = "total \(totalSize)" + unit
                sharedTotalSize = "\(totalSize)"
            }else if unitValue == 1024 {
                unit = "GB"
                totalMemoryLabel.text = "total \(totalSize) " + unit
                sharedTotalSize = "\(totalSize * 1024)"
            }else if unitValue == 1024 * 1024 {
                unit = "TB"
                totalMemoryLabel.text = "total \(totalSize) " + unit
                sharedTotalSize = "\(totalSize * 1024 * 1024)"
            }
            UserInfoManager.shared().limit_data_total_size = sharedTotalSize
            
            var userdData : Double = 0
            if status.monthly_rx_bytes != nil && status.monthly_rx_bytes!.count > 0 {
                userdData += Double(status.monthly_rx_bytes!)!
            }
            if status.monthly_tx_bytes != nil && status.monthly_tx_bytes!.count > 0 {
                userdData += Double(status.monthly_tx_bytes!)!
            }
            
            let leftSize = totalSize * Double(unitValue) - userdData / 1024 / 1024
            
            remianMemory = CGFloat(leftSize)
            
            leftMemoryLabel.text = String(format: "left %.2f%@", leftSize > 0 ? leftSize : 0, "MB")
            
            if leftSize > Double(sharedTotalSize)! {
                
                usedPercent = 100
                
            }else{
                
                let used = ((Double(sharedTotalSize)! - leftSize) / Double(sharedTotalSize)!) * 100
                if used > 0 && used < 1 {
                    usedPercent = 1
                }else {
                    usedPercent = Int(used)
                }
                
              
                
            }
          
        }else {
            let totalTime = Double(totalStr!)!
            totalMemoryLabel.text = String(format: "total %.2fhours", totalTime)
            var userdData : Double = 0
            if status.monthly_time != nil && status.monthly_time!.count > 0 {
                userdData += Double(status.monthly_time!)!
            }
            if status.realtime_time != nil && status.realtime_time!.count > 0 {
                userdData += Double(status.realtime_time!)!
            }
            
            let leftTime = (totalTime * 60 * 60 - userdData) / (60 * 60)
            
            remianMemory = CGFloat(leftTime)
            
            leftMemoryLabel.text = String(format: "%.2f hours", leftTime > 0 ? leftTime : 0)
            
            let used = ((totalTime - leftTime) / totalTime) * 100
            if used > 0 && used < 1 {
                usedPercent = 1
            }else {
                usedPercent = Int(used)
            }
            UserInfoManager.shared().limit_time_total_size = "\(Int(totalTime))"
        }
        changeMemoryDraw()
        
        if !UserInfoManager.shared().data_volume_limit_switch {
            leftMemoryLabel.text = nil
            totalMemoryLabel.text = nil
        }
        
        layoutIfNeeded()
    }
}
